import type { Ref } from 'vue'

type GetListFunction<T> = (params: any) => Promise<ResultData<PageResult<T>>>
/**
 * 表格分页Hook
 * @param getList 请求方法
 * @param params 请求参数
 * @param callback 回调
 */
export function useTablePaging<T, P extends PageQo>(getList: GetListFunction<T>, params: P, callback?: (data: T[]) => void): {
  loadedTable: () => void
  loading: Ref<boolean>
  tableData: Ref<T[]>
  paginationChange: (paging: number, size: number) => void
} {
  // 加载中
  const loading = ref(false)
  // 表格数据
  const tableData: Ref<T[]> = ref([])

  // 获取表格数据
  function loadedTable() {
    loading.value = true
    getList(params).then((res) => {
      params.total = Number(res.data.total)
      tableData.value = res.data.rows
      loading.value = false
      // 回调
      callback && callback(res.data.rows)
    })
  }
  // 分页
  function paginationChange(paging: number, size: number) {
    params.pageNum = paging
    params.pageSize = size
    loadedTable()
  }

  return {
    loadedTable,
    loading,
    tableData,
    paginationChange,
  }
}
